package com.mars.module.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mars.common.constant.Constant;
import com.mars.common.request.sys.ResourceInfoRequest;
import com.mars.common.response.PageInfo;
import com.mars.common.util.DateUtils;
import com.mars.common.util.HttpUtils;
import com.mars.module.system.entity.ResourceInfo;
import com.mars.module.system.mapper.ResourceInfoMapper;
import com.mars.module.system.service.IResourceInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 菜单Service
 *
 * @author 程序员Mars
 */
@Slf4j
@Service
@AllArgsConstructor
public class IResourceInfoServiceImpl implements IResourceInfoService {

    private final ResourceInfoMapper resourceInfoMapper;

    @Override
    public PageInfo<ResourceInfo> pageList(ResourceInfoRequest request) {
        LambdaQueryWrapper<ResourceInfo> wrapper = Wrappers.lambdaQuery(ResourceInfo.class)
                .like(StringUtils.isNotEmpty(request.getTitle()), ResourceInfo::getBusinessTitle, request.getTitle())
                .like(StringUtils.isNotEmpty(request.getMobile()), ResourceInfo::getMobile, request.getMobile());
        if (request.getType() > 0) {
            wrapper.eq(ResourceInfo::getType, request.getType());
        }
        IPage<ResourceInfo> page = resourceInfoMapper.selectPage(request.page(), wrapper);
        return PageInfo.build(page);
    }

    @Override
    public void fetchData(Integer type, Integer page) throws IOException {
        resourceInfoMapper.delete(Wrappers.lambdaQuery(ResourceInfo.class).eq(ResourceInfo::getType, type));
        for (int i = 1; i <= page; i++) {
            HashMap<String, String> headers = buildHeaders();
            String url = "";
            if (type == 0) {
                url = String.format(Constant.ALL_ESOBAO_URL, i);
            } else {
                url = String.format(Constant.ESOBAO_URL, type, i);
            }
            log.info("请求地址:{}", url);
            String data = HttpUtils.sendGet(url, headers);
            log.info("返回参数:{}", data);

            if (StringUtils.isNotEmpty(data)) {
                JSONArray jsonArray = JSONObject.parseArray(data);
                List<ResourceInfo> list = new ArrayList<>();
                for (int j = 0; j < jsonArray.size(); j++) {
                    String businessTitle = jsonArray.getJSONObject(j).getString("business_title");
                    String contacts = jsonArray.getJSONObject(j).getString("contacts");
                    String mobile = jsonArray.getJSONObject(j).getString("mobile");
                    String businessPrice = jsonArray.getJSONObject(j).getString("business_price");
                    String businessTime = jsonArray.getJSONObject(j).getString("business_time");
                    String time = DateUtils.timestampToString(Integer.parseInt(businessTime));
                    JSONArray cityArray = jsonArray.getJSONObject(j).getJSONArray("city");

                    List<String> addressList = new ArrayList<>();
                    if (cityArray.size() > 0) {
                        for (int m = 0; m < cityArray.size(); m++) {
                            String typeName = cityArray.getJSONObject(m).getString("TypeName");
                            addressList.add(typeName);
                        }
                    }
                    String address = String.join("/", addressList);
                    ResourceInfo resourceInfo = ResourceInfo.builder()
                            .businessPrice(businessPrice)
                            .address(address)
                            .businessTime(time)
                            .contacts(contacts)
                            .businessTitle(businessTitle)
                            .type(type)
                            .mobile(mobile).build();
                    list.add(resourceInfo);
                    resourceInfoMapper.insert(resourceInfo);
                    log.info("数据保存成功~");
                }
            }
        }
    }


    /**
     * 构建header请求
     *
     * @return HashMap<String, String>
     */
    public static HashMap<String, String> buildHeaders() {
        HashMap<String, String> map = new HashMap<>();
        map.put("Host", "ntoo8jie.esobao.cn");
        map.put("Accept", "*/*");
        map.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x6309080f) XWEB/8461 Flue");
        map.put("X-Requested-With", "XMLHttpRequest");
        map.put("Referer", "http://ntoo8jie.esobao.cn/index/index.html?code=071Nsu100Dra2R1YZF200mywgQ0Nsu1N&state=");
        map.put("Accept-Encoding", "gzip, deflate");
        map.put("Accept-Language", "zh-CN,zh;q=0.9");
        map.put("Cookie", "PHPSESSID=hvko9fg5gka2pgho5du7te51bv");
        map.put("Connection", "keep-alive");
        return map;
    }

}
